package com.usian.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.model.admin.dtos.NewsAuthDto;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmNewsDto;
import com.usian.model.media.dtos.WmNewsPageReqDto;
import com.usian.model.media.pojos.*;
import com.usian.utils.threadlocal.WmThreadLocalUtils;
import com.usian.wemedia.mapper.WmMaterialMapper;
import com.usian.wemedia.mapper.WmNewsMapper;
import com.usian.wemedia.mapper.WmNewsMaterialMapper;
import com.usian.wemedia.mapper.WmUserMapper;
import com.usian.wemedia.service.WmNewsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;


@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Value("${fileServerUrl}")
    private String fileServerUrl;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;


    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Autowired
    private KafkaTemplate kafkaTemplate;

    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Autowired
    private WmUserMapper wmUserMapper;


    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        //1.校验参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        //2.构造条件
        QueryWrapper<WmNews> queryWrapper = new QueryWrapper<>();
        //状态
        if (dto.getStatus() != null) {

            queryWrapper.lambda().eq(WmNews::getStatus, dto.getStatus());
        }
        //关键字
        if (StringUtils.isNotBlank(dto.getKeyword())) {
            queryWrapper.lambda().like(WmNews::getTitle, dto.getKeyword());
        }
        //频道
        if (dto.getChannelId() != null) {
            queryWrapper.lambda().eq(WmNews::getChannelId, dto.getChannelId());
        }
        //发布时间
        if (dto.getBeginPubDate() != null && dto.getEndPubDate() != null) {
            queryWrapper.lambda().between(WmNews::getPublishTime, dto.getBeginPubDate(), dto.getEndPubDate());
        }
        //用户id
        WmUser user = WmThreadLocalUtils.getUser();
        if (user != null) {
            queryWrapper.lambda().eq(WmNews::getUserId, user.getId());
        }
        queryWrapper.lambda().orderByDesc(WmNews::getCreatedTime);
        //3.封装结果
        Page page = new Page(dto.getPage(), dto.getSize());
        IPage result = page(page, queryWrapper);
        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) result.getTotal());
        /*List<WmNews> date = result.getRecords();
        for (WmNews wmNews : date) {
            wmNews.setImages(a+wmNews.getImages());
        }*/
        responseResult.setData(result.getRecords());
        responseResult.setHost(fileServerUrl);
        return responseResult;
    }

    public static final Short COLLECT_MATERIAL = 1;//收藏
    public static final Short CANCEL_COLLECT_MATERIAL = 0;//收藏
    public static final String WM_NEWS_TYPE_IMAGE = "image";
    public static final Short WM_NEWS_NONE_IMAGE = 0;
    public static final Short WM_NEWS_SINGLE_IMAGE = 1;
    public static final Short WM_NEWS_MANY_IMAGE = 3;
    public static final Short WM_NEWS_TYPE_AUTO = -1;//封面图片自动
    public static final Short WM_CONTENT_REFERENCE = 0;
    public static final Short WM_COVER_REFERENCE = 1;
    public static final short WM_NEWS_CONTENT_REFERENCE = 1;//主图引用

    @Override
    public ResponseResult saveNews(WmNewsDto dto, Short isSubmit) {
        //1.校验参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //保存wmnews表
        WmNews wmNews = new WmNews();
        //深拷贝 浅拷贝
        BeanUtils.copyProperties(dto, wmNews);
        //判断无图自动设置封面
        if (WM_NEWS_TYPE_AUTO.equals(dto.getType())) {
            wmNews.setType(null);
        }
        //过滤图片格式
        if (dto.getImages() != null && dto.getImages().size() > 0) {
            String imageStr = dto.getImages().toString().replace("[", "").replace("]", "")
                    .replace(fileServerUrl, "").replace(" ", "");
            wmNews.setImages(imageStr);
        }
        this.saveWmNews(wmNews, isSubmit);

        //保存 文章内容图片和素材的关系表
        String content = dto.getContent();
        List<Map> imageList = JSON.parseArray(content, Map.class);
        List<String> contentImageList = this.ectractUrlInfo(imageList);
        //提交的时候维护素材关系表
        if (isSubmit == WmNews.Status.SUBMIT.getCode() && contentImageList.size() > 0) {
            ResponseResult result = this.saveRelativeInfoForContent(contentImageList, wmNews.getId());
            if (result.getCode() != 0) {
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }
        }
        //保存封面与素材表
        if (isSubmit == WmNews.Status.SUBMIT.getCode()) {
            ResponseResult result = this.saveRelativeInfoForCover(dto, contentImageList, wmNews);
            if (result.getCode() != 0) {
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /***
     * 根据id查询
     * @param newId
     * @return
     */
    @Override
    public ResponseResult findWmNewsById(Integer newId) {
        if (newId == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews news = this.getById(newId);
        ResponseResult result = ResponseResult.okResult(news);
        result.setHost(fileServerUrl);
        return result;
    }

    /***
     * 根据id删除
     * @param id
     * @return
     */
    @Override
    public ResponseResult delNews(Integer id) {
        //校验参数
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文章id不可缺少");
        }
        //获取数据
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文章不存在");
        }
        //3.判断当前文章的状态  status==9  enable == 1
        if (wmNews.getStatus() == 9 && wmNews.getEnable() == 1) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章已发布，不能删除");
        }
        //去除素材与文章的关系
        wmNewsMaterialMapper.delete(Wrappers.
                <WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));
        //删除文章
        removeById(wmNews.getId());
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /***
     * 上架 下架
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        //校验参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //查询文章
        WmNews wmNews = getById(dto.getId());
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文章不存在");
        }
        //判断文章是否发布
        if (wmNews.getStatus() != 9) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "当前文章不是发布状态，不能上下架");
        }
        //修改文章状态 同步到app端
        if (dto.getEnable() != null && dto.getEnable() > -1 && dto.getEnable() < 2) {
            if (wmNews.getArticleId()!=null){
                Map<String,Object>mesMap=new HashMap<>();
                mesMap.put("enable",dto.getEnable());
                mesMap.put("articleId",wmNews.getArticleId());
                kafkaTemplate.send("down_topic",JSON.toJSONString(mesMap));
            }
            update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId, dto.getId()).set(WmNews::getEnable, dto.getEnable()));

        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
    /**
     * 查询需要发布的文章id列表
     * @return
     */
    @Override
    public List<Integer> findRelease() {
        List<WmNews> list = list(Wrappers.<WmNews>lambdaQuery().eq(WmNews::getStatus, 8).lt(WmNews::getPublishTime, new Date()));
        List<Integer>integerList=list.stream().map(WmNews::getId).collect(Collectors.toList());
        return integerList;
    }
    /**
     * 分页查询文章信息
     * @param dto
     * @return
     */
    @Override
    public PageResponseResult findListAndPage(NewsAuthDto dto) {
        //1:;检查参数
        if (dto==null){
            return (PageResponseResult)ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        //设置起始页
        dto.setPage((dto.getPage()-1)*dto.getSize());
        //分页查询
        List<WmNewsVo> list = wmNewsMapper.findListAndPage(dto);
        //统计查询
        int count = wmNewsMapper.findListCount(dto);
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), count);
        pageResponseResult.setData(list);
        return pageResponseResult;
    }

    /**
     * 查询文章详情
     * @param id
     * @return
     */
    @Override
    public WmNewsVo findWmNewsVo(Integer id) {
        //1.查询文章信息
        WmNews wmNews = getById(id);
        //2.查询作者
        WmUser wmUser = null;
        if(wmNews!=null && wmNews.getUserId() != null){
            wmUser = wmUserMapper.selectById(wmNews.getUserId());
        }
        wmUserMapper.selectById(wmUser.getId());
        //3.封装vo信息返回
        WmNewsVo wmNewsVo = new WmNewsVo();
        BeanUtils.copyProperties(wmNews,wmNewsVo);
        if (wmUser!=null){
            wmNewsVo.setAuthorName(wmUser.getName());
        }
        return wmNewsVo;
    }

    //处理封面图片
    private ResponseResult saveRelativeInfoForCover(WmNewsDto dto, List<String> contentImageList, WmNews wmNews) {
        //如果配置的是自动才会分配封面图片
        List<String> images = dto.getImages();
        if (dto.getType().equals(WM_NEWS_TYPE_AUTO)) {
            //内容中的图片数量小于等于2  设置为单图
            if (contentImageList.size() > 0 && contentImageList.size() <= 2) {
                wmNews.setType(WM_NEWS_SINGLE_IMAGE);
                images = contentImageList.stream().limit(1).collect(Collectors.toList());
            } else if (contentImageList.size() > 2) {
                //如果内容中的图片大于2 则设置为多图
                wmNews.setType(WM_NEWS_MANY_IMAGE);
                images = contentImageList.stream().limit(3).collect(Collectors.toList());
            } else {
                //内容中没有图片，则是无图
                wmNews.setType(WM_NEWS_NONE_IMAGE);
            }
        }
        //过滤一下图片中的格式
        if (images != null && images.size() > 0) {
            wmNews.setImages(images.toString().replace("[", "")
                    .replace("]", "").replace(fileServerUrl, "")
                    .replace(" ", ""));
        }
        this.updateById(wmNews);
        //封面图关系表
        ArrayList<String> materials = new ArrayList<>();
        for (String url : images) {
            materials.add(url.replace(fileServerUrl, ""));
        }
        ResponseResult responseResult = this.saveRelativeInfoForContent(materials, wmNews.getId());
        if (responseResult != null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /***
     * 保存
     * @param wmNews
     * @param isSubmit
     */
    public static final String WM_NEWS_AUTO_SCAN_TOPIC = "wm.news.auto.scan.topic";

    private void saveWmNews(WmNews wmNews, Short isSubmit) {
        wmNews.setStatus(isSubmit);
        WmUser wmUser = WmThreadLocalUtils.getUser();
        boolean flag = false;
        if (wmUser != null) {
            wmNews.setUserId(wmUser.getId());
        }
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable((short) 1);
        if (wmNews.getId() == null) {
            flag = this.save(wmNews);
        } else {
            //先删除关系表在更新主表
            LambdaQueryWrapper<WmNewsMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(WmNewsMaterial::getNewsId, wmNews.getId());
            wmNewsMaterialMapper.delete(lambdaQueryWrapper);
            flag = this.updateById(wmNews);
        }
        if (flag) {
            kafkaTemplate.send("News_Topic", JSON.toJSONString(wmNews.getId()));
        }
    }

    private ResponseResult saveRelativeInfoForContent(List<String> contentImageList, Integer newsId) {
        QueryWrapper<WmMaterial> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().in(WmMaterial::getUrl, contentImageList);
        WmUser user = WmThreadLocalUtils.getUser();
        if (user != null) {
            queryWrapper.lambda().eq(WmMaterial::getUserId, user.getId());
        }
        List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(queryWrapper);
        /***
         * 循环素材库对比
         * List集合转Map集合
         */
        Map<String, Integer> uriIdMap = wmMaterials.stream().collect(Collectors.toMap(WmMaterial::getUrl, WmMaterial::getId));
        ArrayList<String> materialsIds = new ArrayList<>();
        for (String url : contentImageList) {
            Integer id = uriIdMap.get(url);
            if (id == null) {
                //图片不在素材库中 返回无效参数
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            } else {
                //图片在素材库中
                materialsIds.add(id.toString());
            }
        }

        wmNewsMaterialMapper.saveRelationsByContent(materialsIds, newsId, 1);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 提取图片信息
     * 把url提取出来放进list
     *
     * @param
     * @return
     */

    private List<String> ectractUrlInfo(List<Map> list) {
        List<String> imageList = new ArrayList<>();
        for (Map map : list) {
            if (map.get("type").equals(WM_NEWS_TYPE_IMAGE)) {
                String imgUrl = (String) map.get("value");
                imgUrl = imgUrl.replace(fileServerUrl, "");
                imageList.add(imgUrl);
            }
        }
        return imageList;
    }
}
